<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Utils
 *
 * @author QuangKhoi
 */
class Utils {

    //put your code here

    public static function humanTiming($time) {
        //1378960792
        //1386349200
        $time = time() - $time; // to get the time since that moment
        if ($time < 0)
            return "now";
        $tokens = array(
            31536000 => 'year',
            2592000 => 'month',
            604800 => 'week',
            86400 => 'day',
            3600 => 'hour',
            60 => 'minute',
            1 => 'second'
        );
        foreach ($tokens as $unit => $text) {
            if ($time < $unit)
                continue;
            $numberOfUnits = floor($time / $unit);
            return $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's ago' : ' ago');
        }
    }

    public static function detectSentiment($data) {
        $score = 0;
        $words = SentimentWords::getWords();
        $data = mb_strtolower($data, "utf8");
        foreach ($words as $word) {
            $appearCount = substr_count($data, ' ' . $word["word"] . ' ');
            if (strpos($data, $word["word"] . ' '))
                $appearCount++;
            if (strpos($data, ' ' . $word["word"]) + strlen($word["word"]) + 1 == strlen($data))
                $appearCount++;
            if ($data == $word["word"])
                $appearCount = 1;
            $score += $appearCount * $word["score"];
        }
        $finalScore = $score == 0 ? 0 : ($score > 0 ? 1 : -1);
        return $finalScore;
    }

    public static function getDayOfWeek($date) {
        $d = $date->format('w');
        $dayInWeek[0] = 'Sunday';
        $dayInWeek[1] = 'Monday';
        $dayInWeek[2] = 'Tuesday';
        $dayInWeek[3] = 'Wednesday';
        $dayInWeek[4] = 'Thursday';
        $dayInWeek[5] = 'Friday';
        $dayInWeek[6] = 'Saturday';
        return $dayInWeek[$d];
    }

    public static function nl2p($string, $line_breaks = true, $xml = true) {

        $string = str_replace(array('<p>', '</p>', '<br>', '<br />'), '', $string);

        // It is conceivable that people might still want single line-breaks
        // without breaking into a new paragraph.
        if ($line_breaks == true)
            return '<p>' . preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", '$1<br' . ($xml == true ? ' /' : '') . '>$2'), trim($string)) . '</p>';
        else
            return '<p>' . preg_replace(
                            array("/([\n]{2,})/i", "/([\r\n]{3,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", "</p>\n<p>", '$1<br' . ($xml == true ? ' /' : '') . '>$2'), trim($string)) . '</p>';
    }

    public static function get_domain($url) {
        $pieces = parse_url($url);
        $domain = isset($pieces['host']) ? $pieces['host'] : '';
        if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
            return $regs['domain'];
        }
        return false;
    }

    public static function getTitle($Url) {
        $str = file_get_contents($Url);
        if (strlen($str) > 0) {
            preg_match("/\<title\>(.*)\<\/title\>/", $str, $title);
            return $title[1];
        }
    }

    public static function get_client_ip() {
        $ipaddress = '';
        if ($_SERVER['HTTP_CLIENT_IP'])
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if ($_SERVER['HTTP_X_FORWARDED_FOR'])
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if ($_SERVER['HTTP_X_FORWARDED'])
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if ($_SERVER['HTTP_FORWARDED_FOR'])
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if ($_SERVER['HTTP_FORWARDED'])
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if ($_SERVER['REMOTE_ADDR'])
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else
            $ipaddress = 'UNKNOWN';

        return $ipaddress;
    }

    function strToHex($string) {
        $hex = '';
        for ($i = 0; $i < strlen($string); $i++) {
            $hex .= dechex(ord($string[$i]));
        }
        return $hex;
    }

    public static function sortTags($tags, $desc = true) {
        if (count($tags) == 1)
            return $tags;
        $sortedTags = array();
        if ($desc) {
            $maxTag = self::findMaxTag($tags);
            while ($maxTag) {
                foreach ($maxTag as $key => $value)
                    $sortedTags[$key] = $value;
                $maxTag = self::findMaxTag($tags);
            }
        } else {
            $minTag = self::findMinTag($tags);
            while ($minTag) {
                foreach ($minTag as $key => $value)
                    $sortedTags[$key] = $value;
                $minTag = self::findMinTag($tags);
            }
        }
        foreach ($sortedTags as $key => $value) {
            $sortedTags['tagname'][] = $key;
        }
        return $sortedTags;
    }

    public static function sortPlatforms($platforms, $desc = true) {
        if (count($platforms) == 1)
            return $platforms;
        $sortedTags = array();
        if ($desc) {
            $maxTag = self::findMaxTag($platforms);
            while ($maxTag) {
                foreach ($maxTag as $key => $value)
                    $sortedTags[$key] = $value;
                $maxTag = self::findMaxTag($platforms);
            }
        } else {
            $minTag = self::findMinTag($platforms);
            while ($minTag) {
                foreach ($minTag as $key => $value)
                    $sortedTags[$key] = $value;
                $minTag = self::findMinTag($platforms);
                var_dump($minTag);
            }
        }
        return $sortedTags;
    }

    public static function findMaxTag(&$tags) {
        $max = 0;
        $curObj = array();
        $maxKey = '';
        foreach ($tags as $key => $value) {
            if (isset($value['total']))
                if ($key !== 'tagname') {
                    if ($value['total'] > $max) {
                        $max = $value['total'];
                        $curObj = array();
                        $curObj[$key] = $value;
                        $maxKey = $key;
                    }
                }
        }
        if (count($tags) == 0)
            return NULL;
        unset($tags[$maxKey]);
        return $curObj;
    }

    public static function findMinTag(&$tags) {
        $min = 99999999;
        $curObj = array();
        $minKey = '';
        foreach ($tags as $key => $value) {
            if (isset($value['total']))
                if ($key !== 'tagname') {
                    if ($value['total'] < $min) {
                        $min = $value['total'];
                        $curObj = array();
                        $curObj[$key] = $value;
                        $minKey = $key;
                    }
                }
        }
        unset($tags[$minKey]);
        if (count($tags) == 0)
            return NULL;
        return $curObj;
    }

    public static function getDatesFromRange($start, $end) {
        $realEnd = new DateTime($end);
        $realEnd->add(new DateInterval('P1D'));

        $period = new DatePeriod(
                new DateTime($start), new DateInterval('P1D'), $realEnd
        );

        foreach ($period as $date) {
            $array[] = $date;
        }

        return $array;
    }

    public static function multiRequest($data, $options = array()) {

        // array of curl handles
        $curly = array();
        // data to be returned
        $result = array();

        // multi handle
        $mh = curl_multi_init();

        // loop through $data and create curl handles
        // then add them to the multi-handle
        foreach ($data as $id => $d) {

            $curly[$id] = curl_init();

            $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
            curl_setopt($curly[$id], CURLOPT_URL, $url);
            curl_setopt($curly[$id], CURLOPT_HEADER, 0);
            curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);

            // post?
            if (is_array($d)) {
                if (!empty($d['post'])) {
                    curl_setopt($curly[$id], CURLOPT_POST, 1);
                    curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']);
                }
            }

            // extra options?
            if (!empty($options)) {
                curl_setopt_array($curly[$id], $options);
            }

            curl_multi_add_handle($mh, $curly[$id]);
        }

        // execute the handles
        $running = null;
        do {
            curl_multi_exec($mh, $running);
        } while ($running > 0);


        // get content and remove handles
        foreach ($curly as $id => $c) {
            $result[$id] = curl_multi_getcontent($c);
            curl_multi_remove_handle($mh, $c);
        }

        // all done
        curl_multi_close($mh);

        return $result;
    }

    public static function collapseNumber($number){
        $result = round($number);
        if($result >= 1000000){
            $result = round($result / 1000000, 0).'M';
        } else if($result >= 100000){
            $result = round($result / 100000, 0).'k';
        }
        return $result;
    }
}

?>
